package club.monkeywood.service.buyer.impl;

import club.monkeywood.dto.buyer.BuyerRecommendDTO;
import club.monkeywood.dto.buyer.RatingDTO;
import club.monkeywood.dataobject.Rating;
import club.monkeywood.repository.BuyerRecommendRepository;
import club.monkeywood.repository.RatingRepository;
import club.monkeywood.service.buyer.RatingService;
import club.monkeywood.vo.buyer.RatingVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RatingServiceImpl implements RatingService {

    @Autowired
    private RatingRepository ratingRepository;

    @Autowired
    private BuyerRecommendRepository buyerRecommendRepository;

    @Override
    public List<Rating> findAllBySellerId(Sort sort, Integer id) {
        return ratingRepository.findAllBySellerId(sort, id);
    }

    @Override
    public List<Rating> findAllBySellerId(Integer id) {
        Sort.Order order = Sort.Order.desc("deliveryTime");
        Sort sort = Sort.by(order);
        return ratingRepository.findAllBySellerId(sort, id);
    }

    @Override
    public List<RatingDTO> queryProductionRatingBySellerId(Integer sellerId) {
        return ratingRepository.queryBySellerId(sellerId);
    }

    @Override
    public List<RatingVO> queryRatingBySellerId(Integer sellerId) {
        List<RatingDTO> ratingDTOList = ratingRepository.queryBySellerId(sellerId);
        List<BuyerRecommendDTO> buyerRecommendDTOList = buyerRecommendRepository.queryBuyerRecommend(sellerId);
        List<RatingVO> ratingVOList = ratingDTOList.stream()
                                        .map(e->{
                                            RatingVO ratingVO = new RatingVO();
                                            BeanUtils.copyProperties(e, ratingVO);
                                            List<String> recommend = buyerRecommendDTOList.stream()
                                                                        .filter(r->r.getRatingId().equals(e.getId()))
                                                                        .map(item->item.getProductionName())
                                                                        .collect(Collectors.toList());
                                            ratingVO.setRecommend(recommend);
                                            return ratingVO;
                                        })
                                        .collect(Collectors.toList());
        return ratingVOList;
    }

}
